//
//  JYBaseWebViewController.m
//  FinderBox
//
//  Created by JiYi on 2018/10/11.
//  Copyright © 2018 JiYi. All rights reserved.
//

#import "JYBaseWebViewController.h"
#import <WebKit/WebKit.h>

#import "JYHomeWebViewController.h"

@interface JYBaseWebViewController ()<UIWebViewDelegate, WKUIDelegate, WKNavigationDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIProgressView * progressView;



@end

@implementation JYBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupComWeb];
    
    [self setupBridge];
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
}

#pragma mark - Bridge初始化
- (void)setupBridge {
    [JYWKWebViewJavascriptBridgeBase enableLogging];
    
    _bridge = [[JYWKWebViewJavascriptBridge alloc] initWithWebView:self.commonWeb];

    /**
     *  打开新的页面
     */
    [_bridge registerHandler:@"openWindow" handler:^(id data, Callback responseCallback) {
        if ([data valueForKey:@"url"]) {
            NSString * url = data[@"url"];
            JYSubWebViewController * homwebVC = [[JYSubWebViewController alloc] init];
            homwebVC.urlStr = url;
            homwebVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:homwebVC animated:YES];
        }
    }];
    /**
     *  关闭页面
     */
    [_bridge registerHandler:@"closeWindow" handler:^(id data, Callback responseCallback) {
        if (data[@"refresh"]) {
            //  做页面刷新
            
            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userFreshNoti" object:nil];
        }
    }];
    /**
     *  提示框
     */
    [_bridge registerHandler:@"hud" handler:^(id data, Callback responseCallback) {
        if ([data valueForKey:@"type"]) {
            NSString * type = data[@"type"];
            if ([type isEqualToString:@"loading"]) {
//                [SVProgressHUD showWithStatus:data[@"msg"]];
                [MBProgressHUD showInfoMessage:data[@"msg"]];
            }else if ([type isEqualToString:@"hide"]) {
//                [SVProgressHUD dismiss];
                [MBProgressHUD hideHUD];
            }else if ([type isEqualToString:@"success"]) {
//                [SVProgressHUD showSuccessWithStatus:data[@"msg"]];
                [MBProgressHUD showSuccessMessage:data[@"msg"]];
            }else if ([type isEqualToString:@"fail"]) {
//                [SVProgressHUD showErrorWithStatus:data[@"msg"]];
                [MBProgressHUD showErrorMessage:data[@"msg"]];
            }else {
//                [SVProgressHUD dismiss];
                [MBProgressHUD hideHUD];
            }
        }
    }];
    
    /**
     *  自定义弹窗
     */
    [_bridge registerHandler:@"customWindow" handler:^(id data, Callback responseCallback) {
        if ([data valueForKey:@"url"]) {
            NSString * url = data[@"url"];
            
            JYSubWebViewController * homwebVC = [[JYSubWebViewController alloc] init];
            homwebVC.urlStr = url;
            homwebVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:homwebVC animated:YES];
        }
    }];
    [_bridge registerHandler:@"closeCustomWindow" handler:^(id data, Callback responseCallback) {
        if (data[@"animated"]) {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }else {
            [self dismissViewControllerAnimated:NO completion:^{
                
            }];
        }
    }];
    
    /**
     *  操作表
     */
    [_bridge registerHandler:@"actionsheet" handler:^(id data, Callback responseCallback) {
        if (data) {
            NSMutableDictionary * dataDict = [NSMutableDictionary dictionaryWithDictionary:data];
            
            NSMutableArray * actionArr = [NSMutableArray array];
            NSMutableArray * titleArr = [NSMutableArray array];
            for (NSString * key in dataDict.allKeys) {
                [titleArr addObject:key];
                [actionArr addObject:[dataDict valueForKey:key]];
            }
            
            NSMutableArray * modelArr = [NSMutableArray array];
            for (int i = 0; i < titleArr.count; i++) {
                NSString * tempTitle = titleArr[i];
                [modelArr addObject:[[JYSelectedListModel alloc] initWithSid:i Title:tempTitle]];
            }
            
            JYSelectedListView *view = [[JYSelectedListView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), 0) style:UITableViewStylePlain];
            
            view.isSingle = YES;
            
            view.array = modelArr.copy;

            view.selectedBlock = ^(NSArray<JYSelectedListModel *> *array) {
                [LEEAlert closeWithCompletionBlock:^{
                    JYSelectedListModel * model = array.firstObject;
                    [self.bridge callHandler:@"linkFun" data:nil responseCallback:^(id responseData) {
                        
                    }];
                    [self.bridge callHandler:actionArr[model.sid] data:nil responseCallback:^(id responseData) {
                        
                    }];
                }];

            };
            
            [LEEAlert actionsheet].config
            .LeeTitle(@"请选择操作选项")
            .LeeItemInsets(UIEdgeInsetsMake(20, 0, 20, 0))
            .LeeAddCustomView(^(LEECustomView *custom) {
                
                custom.view = view;
                
                custom.isAutoWidth = YES;
            })
            .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
            .LeeAddAction(^(LEEAction *action) {
                
                action.title = @"取消";
                
                action.titleColor = [UIColor blackColor];
                
                action.backgroundColor = [UIColor whiteColor];
            })
            .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
            .LeeHeaderColor([UIColor colorWithRed:243/255.0f green:243/255.0f blue:243/255.0f alpha:1.0f])
            .LeeActionSheetBottomMargin(0.0f) // 设置底部距离屏幕的边距为0
            .LeeCornerRadius(0.0f) // 设置圆角曲率为0
            .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
                return CGRectGetWidth([[UIScreen mainScreen] bounds]);
            })
            .LeeShow();
            
          
        }
    }];
    
    
    //  保存图片
    [_bridge registerHandler:@"savePhoto" handler:^(id data, Callback responseCallback) {
        if ([data containsValueForKey:@"data"]) {
            if (data[@"data"]) {
                //  保存图片
                [self savePhotoWithBase64String:data[@"data"]];
            }
        }
    }];
    
    
    [_bridge registerHandler:@"device" handler:^(id data, Callback responseCallback) {
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        NSDictionary * infoDict = [NSBundle mainBundle].infoDictionary;
        [dict setObject:[NSBundle mainBundle].bundleIdentifier forKey:@"bundId"];
        [dict setObject:infoDict[@"CFBundleShortVersionString"] forKey:@"appVersion"];
        [dict setObject:infoDict[@"CFBundleVersion"] forKey:@"appBuildVersion"];
        [dict setObject:infoDict[@"CFBundleName"] forKey:@"appName"];
        [dict setObject:infoDict[@"CFBundleDisplayName"] forKey:@"appDispaleyname"];
        [dict setObject:[[UIDevice alloc]init].systemName forKey:@"systemName"];
        [dict setObject:[[UIDevice alloc]init].systemVersion forKey:@"systemVersion"];
        [dict setObject:[[UIDevice alloc]init].name forKey:@"deviceName"];
        [dict setObject:[[UIDevice alloc]init].identifierForVendor.UUIDString forKey:@"uuid"];
        [dict setObject:[[UIDevice alloc]init].model forKey:@"model"];
        [dict setObject:[[UIDevice alloc]init].localizedModel forKey:@"loaclName"];
        
        responseCallback(dict);
    }];
    
    [_bridge registerHandler:@"photoLibrary" handler:^(id data, Callback responseCallback) {
        //  选择图片
        [self chooseImagePick];
    }];
    
    
    [_bridge registerHandler:@"pay" handler:^(id data, Callback responseCallback) {
        [SVProgressHUD showErrorWithStatus:@"还么有对接支付哦"];
    }];
    
    [_bridge registerHandler:@"selectTabBar" handler:^(id data, Callback responseCallback) {
        NSString * index =  [NSString stringWithFormat:@"%@",data[@"index"]];
        JYTabBarController * mainTab = (JYTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        mainTab.selectedIndex = index.integerValue;
    }];

    
    
    
    
    
    
    /**
     *  保存用户数据
     */
    [_bridge registerHandler:@"saveUserData" handler:^(id data, Callback responseCallback) {
        
        if (data) {
            NSMutableDictionary * dataDict = [NSMutableDictionary dictionaryWithDictionary:data];
            
            for (NSString * key in dataDict.allKeys) {
                [[NSUserDefaults standardUserDefaults] setValue:[dataDict valueForKey:key] forKey:key];
                
            }
            responseCallback(@"1");
        }else {
            responseCallback(@"0");
        }
    }];
    [_bridge registerHandler:@"getUserData" handler:^(id data, Callback responseCallback) {
        if (data) {
            NSMutableDictionary * dataDict = [NSMutableDictionary dictionaryWithDictionary:data];
            
            
            NSMutableDictionary * tempDict = [NSMutableDictionary dictionary];
            
            
            for (NSString * key in dataDict.allKeys) {
                if ([[NSUserDefaults standardUserDefaults] valueForKey:key] != nil) {
                    [tempDict setValue:[[NSUserDefaults standardUserDefaults] valueForKey:key] forKey:key];
                }
            }
            if (tempDict.count == 0) {
                responseCallback(dataDict);
            }else {
                responseCallback(tempDict);
            }

        }
    }];
    /**
     *  删除数据
     */
    [_bridge registerHandler:@"removeUserData" handler:^(id data, Callback responseCallback) {
        if (data) {
            NSMutableDictionary * dataDict = [NSMutableDictionary dictionaryWithDictionary:data];
            for (NSString * key in dataDict.allKeys) {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
            }
        }
    }];
}
#pragma mark - 初始化com
- (void)setupComWeb {
    _commonWeb = [[WKWebView alloc] init];
    [self.view addSubview:_commonWeb];
    _commonWeb.backgroundColor = UIColor.whiteColor;
    _commonWeb.opaque = NO;
    
    
    _commonWeb.UIDelegate = self;
    _commonWeb.navigationDelegate = self;
    [_commonWeb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    //  载入初始地址
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
    });
    [self.commonWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, CGRectGetWidth(self.view.frame), 2)];
    self.progressView.progressTintColor = JYMainColor;
    self.progressView.backgroundColor = UIColor.whiteColor;
    self.progressView.trackTintColor = UIColor.whiteColor;
    
    [self.view addSubview:self.progressView];
    
    [self.commonWeb addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
}
- (void)dealloc {
    [self.commonWeb removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.commonWeb setNavigationDelegate:nil];
    [self.commonWeb setUIDelegate:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqual:@"estimatedProgress"] && object == self.commonWeb) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.commonWeb.estimatedProgress animated:YES];
        if (self.commonWeb.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:YES];
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 选择图片
- (void)chooseImagePick {
    UIImagePickerController * imagePick = [[UIImagePickerController alloc] init];
    imagePick.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    imagePick.delegate = self;
    [self presentViewController:imagePick animated:YES completion:^{
        
    }];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        // save photo and get asset / 保存图片，获取到asset
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            //  拿到图片
            [self uploadWithImage:image];
        });
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadWithImage:(UIImage *)image {
    
}

#pragma mark - 保存图片
- (void)savePhotoWithBase64String:(NSString *)string {
    UIImage * image = [JYTools stringToImage:string];
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (!error) {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }else {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }
}


#pragma mark - WK
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title;"];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {

}
//  完成加载
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [webView evaluateJavaScript:@"document.title;" completionHandler:^(id ss, NSError * _Nullable error) {
        self.navigationItem.title = ss;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
